package com.chint.springboot.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;

@Data
@Component
public class JwtUtils {

    private static final long EXPIRATION_TIME = 7 * 24 * 60 * 60 * 1000; // 7天过期
    // 生成符合要求的 SecretKey
    private static final Key secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    // 生成JWT
    public String generateToken(String username) {

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() +  EXPIRATION_TIME);

        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);

        return Jwts.builder()
                .addClaims(map)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(secretKey, SignatureAlgorithm.HS256)
                .compact();


    }

    // 解析JWT
    public Claims getClaimsByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // 判断JWT是否过期
    public boolean isTokenExpired(Claims claims) {

        return claims.getExpiration().compareTo(new Date()) > 0;
    }

    public String getHeader() {
        return "Authorization";
    }
}
